﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 3/1/2011
 * Time: 8:30 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TomatoSynchronizer.Entities;
using TomatoSynchronizer.Store;
using HtmlAgilityPack;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace TomatoSynchronizer.Synchronizer
{
	/// <summary>
	/// Description of FaqSynchronizer
	/// </summary>
	public static class FaqSynchronizer
	{
		public static void Synchronize(Site siteSrc,Site siteDest,HtmlWeb client,SyncDirection direction)
		{
			switch(direction)
			{
				case SyncDirection.Download:
					UpLoadItems(siteDest,siteSrc,client,direction);
					break;
				case SyncDirection.Upload:
					UpLoadItems(siteSrc,siteDest,client,direction);
					break;
				case SyncDirection.DownloadAndUpload:
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
				case SyncDirection.UploadAndDownload:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					break;
				case SyncDirection.Synchronize:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					
					FaqStore FaqStoreDest = new FaqStore(siteDest,client);					
					var faqs = FaqStoreDest.DownloadItems();
					
					foreach(Faq faq in faqs)
					{
						bool sync = false;
						
						MappingStore mappingStoreSrc = new MappingStore(siteSrc,siteDest,"faqs_id");
						foreach(Mapping mapping in mappingStoreSrc.Mappings)
						{
							if(mapping.DestValue == faq.faqs_id)
							{
								sync = true;
							}
						}
						
						if(!sync)
						{
							if(!FaqStoreDest.DeleteItem(faq.faqs_id))
							{
								throw new Exception("Could not delete the faq " + faq.faqs_question + " in site " + FaqStoreDest.site.Name);
							}
						}
					}
					break;
			}
		}
		
		private static void UpLoadItems(Site _siteSrc,Site _siteDest,HtmlWeb client,SyncDirection direction)
		{
			FaqStore FaqStoreSrc = new FaqStore(_siteSrc,client);
			FaqStore FaqStoreDest = new FaqStore(_siteDest,client);
			
			Faq[] FaqsSrc =  FaqStoreSrc.LoadItems();
			Faq[] FaqsDest =  FaqStoreDest.LoadItems();
			
			MappingStore mappingStoreSrc = new MappingStore(_siteSrc,_siteDest,"faqs_id");
			MappingStore mappingStoreDest = new MappingStore(_siteDest,_siteSrc,"faqs_id");
			
			mappingStoreSrc.Clean<Faq>(FaqStoreSrc,FaqStoreDest);
			mappingStoreDest.Clean<Faq>(FaqStoreDest,FaqStoreSrc);
			
			MappingStore mappingStore = new MappingStore(_siteSrc,_siteDest,"languages_id");
			
			List<Faq> alreadySynchronized = new List<Faq>();
			
			foreach(Faq FaqSrc in FaqsSrc)
			{
				//we assume the Faq is not yet synchronized
				bool synchronized = false;
				
				//we check if a mapping already exists for this Faq in the destination store
				foreach(Mapping mapping in mappingStoreSrc.Mappings)
				{
					if(mapping.SrcValue == FaqSrc.faqs_id && synchronized == false)
					{
						if(!string.IsNullOrEmpty(mapping.DestValue))
						{
							//this Faq already exists in the destination store
							//we check if everything changed since the last synchronization
							Faq FaqDest = FaqStoreDest.GetItem(mapping.DestValue);
							if(!string.IsNullOrEmpty(FaqDest.faqs_id))
							{
								synchronized = SynchronizeItem(FaqSrc,FaqDest);
							}
							else
							{
								//the mapping exists, but the Faq has been deleted in the destination store
								//we set a flag that this mapping does not exists anymore
								mapping.Exists = false;
							}
						}
					}
				}
				
				if(!synchronized)
				{
					//there is no mapping, we check if this Faq already exists in the destination store
					foreach(Faq FaqDest in FaqsDest)
					{
						foreach(Mapping mapping in mappingStore.Mappings)
						{
							try
							{
								if(FaqSrc.faqs_questions["Faqs_name[" + mapping.SrcValue + "]"] == FaqDest.faqs_questions["Faqs_name[" + mapping.DestValue + "]"] && synchronized == false && !alreadySynchronized.Contains(FaqSrc))
								{
									//we get the 2 currencies from sites to get sure they really exist
									Faq src = FaqSrc.Store.GetItem(FaqSrc.faqs_id);
									Faq dest = FaqDest.Store.GetItem(FaqDest.faqs_id);
									
									if(!string.IsNullOrEmpty(src.faqs_id))
									{
										if(!string.IsNullOrEmpty(dest.faqs_id))
										{
											Mapping _mapping = new Mapping(FaqSrc.faqs_id,FaqDest.faqs_id,"faqs_id");
											mappingStoreSrc.Mappings.Add(_mapping);
											
											synchronized = SynchronizeItem(FaqSrc,FaqDest);
										}
										else
										{
											synchronized = false;
										}
									}
									else
									{
										synchronized = true;
									}
								}
							}
							catch (KeyNotFoundException)
							{
								
							}
						}
						
					}
				}
				
				if(!synchronized)
				{
					//no mapping the Faq is new
					//we insert it in the destination store
					string remoteId = string.Empty;																														
					
					Dictionary<string, string> _faqs_questions = new Dictionary<string, string>();
					Dictionary<string, string> _faqs_urls = new Dictionary<string, string>();
					Dictionary<string, string> _faqs_answers = new Dictionary<string, string>();
					
					MappingStore _mappingStore = new MappingStore(FaqSrc.Store.site,_siteDest,"languages_id");
					foreach(Mapping mapping in _mappingStore.Mappings)
					{
						_faqs_questions["faqs_question[" + mapping.DestValue + "]"] = FaqSrc.faqs_questions["faqs_question[" + mapping.SrcValue + "]"];
						_faqs_urls["faqs_url[" + mapping.DestValue + "]"] = FaqSrc.faqs_urls["faqs_url[" + mapping.SrcValue + "]"];
						_faqs_answers["faqs_answer[" + mapping.DestValue + "]"] = FaqSrc.faqs_answers["faqs_answer[" + mapping.SrcValue + "]"];
					}
					
					FaqSrc.faqs_questions = _faqs_questions;
					FaqSrc.faqs_urls = _faqs_urls;
					FaqSrc.faqs_answers = _faqs_answers;
					
					remoteId = FaqStoreDest.InsertItem(FaqSrc);
					
					synchronized = remoteId != string.Empty;
					
					if(!synchronized)
					{
						throw new Exception("The Faq " + FaqSrc.faqs_id + " has not been synchronized");
					}
					
					Mapping _mapping = new Mapping(FaqSrc.faqs_id,remoteId,"faqs_id");
					mappingStoreSrc.Mappings.Add(_mapping);
					synchronized = true;
				}
				
				if(!synchronized)
				{
					throw new Exception("could not synchronize the Faq " + FaqSrc.faqs_id);
				}
				
//				FaqStoreSrc.PersistItem(FaqSrc);
				alreadySynchronized.Add(FaqSrc);
			}
			
			mappingStoreSrc.Save();
			
			mappingStoreDest.Truncate();
			
			//we save the mappings in the destination MappingStore too
			foreach(Mapping mapping in mappingStoreSrc.Mappings)
			{
				if(mapping.Exists)
				{
					Mapping mappingDest = new Mapping(mapping.DestValue,mapping.SrcValue,mapping.Property);
					mappingStoreDest.Mappings.Add(mappingDest);
				}
			}
			
			mappingStoreDest.Save();
			
			//we check if the 2 MappingStore are synchronized
			if(mappingStoreSrc.Mappings.Count != mappingStoreDest.Mappings.Count)
			{
				throw new Exception("The mapping store for the Faqs are not synchronized");
			}
		}
		
		private static bool SynchronizeItem(Faq FaqSrc,Faq FaqDest)
		{
			bool synchronized = true;
			
			if(!FaqSrc.Equals(FaqDest))
			{
				synchronized = false;
				
				//we update the destination Faq
				FaqSrc.language_id = FaqDest.language_id;
				FaqSrc.faqs_id = FaqDest.faqs_id;
				
				var languages = FaqDest.Store.site.GetLanguageStore().LoadItems();
				
				Dictionary<string, string> _faqs_questions = new Dictionary<string, string>();
				Dictionary<string, string> _faqs_urls = new Dictionary<string, string>();
				Dictionary<string, string> _faqs_answers = new Dictionary<string, string>();
				
				MappingStore mappingStore = new MappingStore(FaqSrc.Store.site,FaqDest.Store.site,"languages_id");
				foreach(Mapping mapping in mappingStore.Mappings)
				{
					_faqs_questions["faqs_question[" + mapping.DestValue + "]"] = FaqSrc.faqs_questions["faqs_question[" + mapping.SrcValue + "]"];
					_faqs_urls["faqs_url[" + mapping.DestValue + "]"] = FaqSrc.faqs_urls["faqs_url[" + mapping.SrcValue + "]"];
					_faqs_answers["faqs_answer[" + mapping.DestValue + "]"] = FaqSrc.faqs_answers["faqs_answer[" + mapping.SrcValue + "]"];
				}
				
				FaqSrc.faqs_questions = _faqs_questions;
				FaqSrc.faqs_urls = _faqs_urls;
				FaqSrc.faqs_answers = _faqs_answers;
				
				synchronized = FaqDest.Store.UpdateItem(FaqSrc);
			}
			
			return synchronized;
		}
		
		private static string UploadItem(FaqStore FaqStoreDest,Faq Faq)
		{
			string remoteId = string.Empty;
			
			remoteId = FaqStoreDest.InsertItem(Faq);
			
			return remoteId;
		}
	}
}
